export default class Common {

  static baseBtnClick(node, cb) {
    let downFontNode = node.getChildByName("down");
    node.on(cc.Node.EventType.TOUCH_START, () => {
      if (downFontNode) {
        downFontNode.active = true;
      }
    })
    node.on(cc.Node.EventType.TOUCH_CANCEL, () => {
      if (downFontNode) {
        downFontNode.active = false;
      }
    })

    node.on(cc.Node.EventType.TOUCH_END, () => {
      if (downFontNode) {
        downFontNode.active = false;
      }
      cb();
    }, this)
  };

  static btnClick(node, cb) {
    this.baseBtnClick(node, () => {
      // cc.game.emit(EVENT.AUDIO + EVENT.POSTFIX, {
      //   target: AUDIOCONTROLLER.BTNCLICK,
      //   action: AUDIOACTION.PLAYSOUND
      // });
      cb(node);
    })

  };

  static showAlert(text, cb){
    cc.find("Canvas/alertPanel").getComponent("alertController").show(text, cb);
  }

  static getUrlParms(name){
   var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
   var r = window.location.search.substr(1).match(reg);
   if(r!=null) return unescape(r[2]);
   return null;
   }

  static menuShaking(node){
    // let flag = !node.getChildByName("active").active;
    node.on(cc.Node.EventType.MOUSE_ENTER, ()=>{
      // if(flag){
        node.getComponent("cc.Animation").play();
      // }
    })

    node.on(cc.Node.EventType.MOUSE_LEAVE, ()=>{
      // if(flag){
        node.getComponent("cc.Animation").stop();
      // }
    })
  }

  static setNodeImg(imgUrl: string, node: cc.Node){
    cc.loader.loadRes("texture/"+imgUrl, cc.SpriteFrame, function (err, spriteFrame) {
      if (err) {
          cc.error(err.message || err);
          return;
      }
      node.getComponent(cc.Sprite).spriteFrame = spriteFrame;
    });
  }


  static asyncGetUrlImg(imgUrl: string, node: cc.Node) {
    // cc.loader.load({ url: Setting.DOMAIN + Setting.CROSSORIGIN + imgUrl, type: 'jpg' }, function (err, tex: cc.Texture2D) {
    //   let spriteFrame = new cc.SpriteFrame();
    //   spriteFrame.setTexture(tex);
    //   node.getComponent(cc.Sprite).spriteFrame = spriteFrame;
    // });
  }

  static setLableNodeText(text: string, node: cc.Node) {
    let nodeLabel = node.getComponent(cc.Label);
    if (nodeLabel) {
      nodeLabel.string = text;
    }
  }


  static getRandomNum(maxNum){
    return Math.floor(Math.random() * maxNum);
  }



  // type: layer||panel
  static loadPrefab(type, name, data){
    let prefabName = name.split("/").reverse()[0];
    let typeNode = cc.find(`Canvas/body/${type}`);
    typeNode.children.map(item=>{item.active = false});

    let target = typeNode.getChildByName(prefabName);
    if(target){
      target.active = true;
      target.getComponent(prefabName).init(data);
      return;
    }

    cc.loader.loadRes(`prefabs/${type}/${name}`, function (err, prefab) {
      let p = cc.instantiate(prefab);
      p.getComponent(prefabName).init(data);
      cc.find(`Canvas/body/${type}`).addChild(p);
    });
  }

  static numberToChinese(num: number) {
    var chnNumChar = ["��", "һ", "��", "��", "��", "��", "��", "��", "��", "��"];
    if (num >= 0 && num <= 9) {
      return chnNumChar[num];
    }
  }

  static getPhoto(imgNode: cc.Node, maskNode: cc.Node, showImg: cc.SpriteFrame) {
    const el = document.createElement('input');
    el.type = "file";
    el.style.display = "none";
    document.body.appendChild(el);
    el.click();

    el.onchange = function (event) {

      maskNode.active = true;

      var file = (event.target as any).files[0];
      if (!/image\/\w+/.test(file.type)) {
        maskNode.active = false;
        return false;
      }
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        var img = new Image();
        img.src = this.result;
        img.onload = function () {
          var canvas = document.createElement("canvas");
          var context = canvas.getContext("2d");

          var width = img.width;
          var height = img.height;

          if (width < 425 || height < 535) {
            maskNode.active = false;
            alert("ͼƬ̫С");
            return;
          }

          canvas.width = 425;
          canvas.height = 535;

          let x, y, w, h;

          if (width >= height) {
            //�Ը߶�Ϊ׼
            x = (width - 425 / 535 * height) / 2;
            y = 0;
            w = 425 / 535 * height;
            h = height;
          } else {
            //�Կ��Ϊ׼
            x = 0;
            y = (height - 535 / 425 * width) / 2;
            w = width;
            h = 535 / 425 * width;
          }

          if (Common.getPhotoOrientation(img) == 6) {
            // let x = (width- height*(535/425))/2;
            context.translate(212.5, 267.5);
            context.rotate(90 * Math.PI / 180);
            if (width == height) {
              context.drawImage(img, 0, 0, height, height * 425 / 535, -267.5, -212.5, 535, 425);
            } else {
              context.drawImage(img, x, y, h, w, -267.5, -212.5, 535, 425);
            }
          } else {
            context.drawImage(img, x, y, w, h, 0, 0, 425, 535);
          }

          var imgURI = canvas.toDataURL("image/jpeg");

          let img2 = new Image();
          img2.src = imgURI;

          img2.onload = function () {

            let texture = new cc.Texture2D();
            texture.initWithElement(img2);

            // let spriteFrame = new cc.SpriteFrame();
            // spriteFrame.setTexture(texture);
            imgNode.getComponent(cc.Sprite).spriteFrame = showImg;
            imgNode.width = 97;
            imgNode.height = 104;
            Common.setLableNodeText(imgURI, imgNode.getChildByName("data"));
            maskNode.active = false;
          }
        };

      }
    };
  }

  static getPhotoOrientation(img) {
    var orient;
    EXIF.getData(img, function () {
      orient = EXIF.getTag(this, 'Orientation');
    });
    return orient;
  }

  static isIphone() {
    let r = true;
    var ua = navigator.userAgent.toLowerCase();
    if (/iphone|ipad|ipod/.test(ua)) {
      r = true;
    }
    return r;
  }

  static copyToClipboard(input) {
    const el = document.createElement('textarea');

    el.value = input;

    // Prevent keyboard from showing on mobile
    el.setAttribute('readonly', '');

    // el.style.contain = 'strict';
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    el.style.fontSize = '12pt'; // Prevent zooming on iOS

    const selection = document.getSelection();
    let originalRange = false;
    if (selection.rangeCount > 0) {
      originalRange = selection.getRangeAt(0) as any;
    }

    document.body.appendChild(el);
    el.select();

    // Explicit selection workaround for iOS
    el.selectionStart = 0;
    el.selectionEnd = input.length;

    let success = false;
    try {
      success = document.execCommand('copy');
    } catch (err) { }

    document.body.removeChild(el);

    if (originalRange) {
      selection.removeAllRanges();
      selection.addRange(originalRange as any);
    }

    alert("���Ƴɹ�!");

  }

  static dateFtt(fmt,date){ //author: meizz
    var o = {
      "M+" : date.getMonth()+1,                 //�·�
      "d+" : date.getDate(),                    //��
      "h+" : date.getHours(),                   //Сʱ
      "m+" : date.getMinutes(),                 //��
      "s+" : date.getSeconds(),                 //��
      "q+" : Math.floor((date.getMonth()+3)/3), //����
      "S"  : date.getMilliseconds()             //����
    };
    if(/(y+)/.test(fmt))
      fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
      if(new RegExp("("+ k +")").test(fmt))
    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
  }


  static formatDateByUnixTimestamp(seconds = 0) {
    let times = '';
    var days = Math.floor(seconds / (3600 * 24));
    if (days > 0) {
      //����7�죬������ʾ��7��ǰ��
      if (days >= 7) days = 7;
      times = days + "��ǰ";
    } else {
      seconds = seconds % (3600 * 24);
      var hours = Math.floor(seconds / 3600);
      if (hours > 0) {
        //����1Сʱ����24Сʱ����ʾСʱ��
        times = hours + "Сʱǰ";
      } else {  //����1Сʱ����ʾ���Ӻ�����
        seconds = seconds % 3600;
        var minutes = Math.floor(seconds / 60);
        if (minutes > 0 && minutes <= 60) {
          times = minutes + "����ǰ";
        } else {
          seconds = seconds % 60;
          times = seconds + "��ǰ";
        }
      }
    }

    return times;
  }

  static formatUserNameByLength7(name: string) {
    if (name.length > 7) {
      return name.substring(0, 7).concat("...");
    }
    return name;
  }

  static getQualityParam(quality:number) {
    if(quality == 4) {
      return 5;
    } else if (quality == 5) {
      return 7;
    } else {
      return quality;
    }
  }

  static getSuitBtScore(_protoId:number, _quality:number) {
    let direct = _protoId % 3;
    let quality = this.getQualityParam(_quality);
    let ret = {attrs: [{attrId: "", attrVal: 0},{attrId: "", attrVal: 0}], btScore: 0};
    let attrs = ret.attrs;
    if (direct == 0) {
      attrs[0].attrVal = (300 + (quality - 1) * 300);
      attrs[0].attrId = "health";
      attrs[1].attrVal = (30 + (quality - 1) * 30);
      attrs[1].attrId = "defence";
      ret.btScore = attrs[0].attrVal / 10 + attrs[1].attrVal;
    } else if (direct == 1) {
      attrs[0].attrVal = (300 + (quality - 1) * 300);
      attrs[0].attrId = "health";
      attrs[1].attrVal = (30 + (quality - 1) * 30);
      attrs[1].attrId = "attack";
      ret.btScore = attrs[0].attrVal / 10 + attrs[1].attrVal;
    } else {
      attrs[0].attrVal = (30 + (quality - 1) * 30);
      attrs[0].attrId = "defence";
      attrs[1].attrVal = (30 + (quality - 1) * 30);
      attrs[1].attrId = "attack";
      ret.btScore = attrs[0].attrVal + attrs[1].attrVal;
    }
    return ret;
  }

  static SuitAttrParam = [
    [{attrId:"attack", fix: 200, rate: 200}, {attrId:"defence", fix: 40, rate: 40}, {attrId:"health", fix: 600, rate: 600}, {attrId:"defence", fix: 60, rate: 60}, {attrId:"health", fix: 400, rate: 400}],
    [{attrId:"attack", fix: 190, rate: 190}, {attrId:"defence", fix: 42, rate: 42}, {attrId:"health", fix: 630, rate: 630}, {attrId:"defence", fix: 63, rate: 63}, {attrId:"health", fix: 420, rate: 420}],
    [{attrId:"attack", fix: 210, rate: 210}, {attrId:"defence", fix: 38, rate: 38}, {attrId:"health", fix: 570, rate: 570}, {attrId:"defence", fix: 57, rate: 57}, {attrId:"health", fix: 380, rate: 380}],
  ];

  static WeaponAttrParam = [
    [0.4, 1.6], [0.5, 1.5], [0.3, 1.7]
  ];
  static getSuitAttr(protoId:number, quality:number, pos:number) {
    let direct = protoId % 3;
    let ret = {attrId: "", attrMin: 0, attrMax: 0};
    let cfg = this.SuitAttrParam[direct][pos - 1];
    ret.attrId = cfg.attrId;
    let _quality = this.getQualityParam(quality);
    let attrVal = cfg.fix + (_quality - 1) * cfg.rate;
    let attrMin = attrVal * 0.9;
    let attrMax = attrVal * 1.1;
    if (pos == 1) {
      let p = this.WeaponAttrParam[direct];
      attrMin *= p[0];
      attrMax *= p[1];
    }
    ret.attrMin = attrMin;
    ret.attrMax = attrMax;
    return ret;
  }
}
